package com.taojin.shoppinginterest.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.taojin.shoppinginterest.R;
import com.taojin.shoppinginterest.activity.SpecialDetailActivity;
import com.taojin.shoppinginterest.adapter.FavoriteFragmentAdapter;
import com.taojin.shoppinginterest.bean.District;
import com.taojin.shoppinginterest.bean.DistrictList;
import com.taojin.shoppinginterest.bean.Favorite;
import com.taojin.shoppinginterest.bean.FavoriteList;
import com.taojin.shoppinginterest.constants.ApiConfig;
import com.taojin.shoppinginterest.pop.PopHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by T400 on 15-5-11.
 */

public class FavorableFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2, AdapterView.OnItemClickListener {
    @ViewInject(R.id.rg_top_favorable)
    private RadioGroup rg;
    @ViewInject(R.id.rb_city_top)
    private RadioButton rb_city;
    @ViewInject(R.id.rb_cityshop_top)
    private RadioButton rb_city_shop;
    @ViewInject(R.id.rb_sort_top)
    private RadioButton rb_sort;
    @ViewInject(R.id.fragment_favorable_PullToRefreshListView)
    private PullToRefreshListView pullToRefreshListView;
    private List<Favorite> listFavorite;

    private List<FavoriteList>   favoriteLists;
    private FavoriteFragmentAdapter favoriteFragmentAdapter;
    private HttpUtils httpUtils;
    private BitmapUtils bitmapUtils;
    private int page = 1;
    private List<DistrictList> districtLists;
    private PopupWindow popupWindow;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_favorable, container, false);
        ViewUtils.inject(this, view);
        getList();
        initData();
        loadData();


        return view;
    }

    @OnClick({R.id.rb_city_top, R.id.rb_cityshop_top, R.id.rb_sort_top})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rb_city_top:
                if (PopHelper.getInstance().isShowing()) {
                    PopHelper.getInstance().dismiss();
                } else {
                    PopHelper.getInstance().init(getActivity(), v, districtLists);
                }
                break;
            case R.id.rb_cityshop_top:
                break;
            case R.id.rb_sort_top:
                break;
        }
    }

    private RequestParams getRequestParams() {
        RequestParams requestParams = new RequestParams();
        requestParams.addBodyParameter("act", "area_district");
        requestParams.addBodyParameter("app", "other");
        requestParams.addBodyParameter("pt", "2");
        requestParams.addBodyParameter("ver", "1.1");
        return requestParams;
    }

    private void getList() {
        districtLists = new ArrayList<>();
        httpUtils = new HttpUtils();

        httpUtils.send(HttpRequest.HttpMethod.POST, ApiConfig.URL, getRequestParams(), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String data = responseInfo.result;
                District district = JSON.parseObject(data, District.class);
                if (district != null) {
                    if (district.getData() != null) {
                        if (district.getData().getDistrict_list() != null && !district.getData().getDistrict_list().isEmpty()) {
                            districtLists.clear();
                            districtLists.addAll(district.getData().getDistrict_list());
                            favoriteFragmentAdapter.notifyDataSetChanged();

                        }
                    }
                    pullToRefreshListView.onRefreshComplete();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });

    }

    private void initData() {
        listFavorite = new ArrayList<>();
        httpUtils = new HttpUtils();
        bitmapUtils = new BitmapUtils(getActivity());
        favoriteFragmentAdapter = new FavoriteFragmentAdapter(listFavorite, getActivity());
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, true, false));
        pullToRefreshListView.setOnItemClickListener(this);
        pullToRefreshListView.setAdapter(favoriteFragmentAdapter);
    }


    private void loadData() {
        RequestParams requestParams = new RequestParams();
        requestParams.addBodyParameter("act", "lists");
        requestParams.addBodyParameter("app", "activity");
        requestParams.addBodyParameter("district", "0");
        requestParams.addBodyParameter("lat", "32.03789");
        requestParams.addBodyParameter("lon", "118.77615");
        requestParams.addBodyParameter("page", String.valueOf(page));
        requestParams.addBodyParameter("perpage", "20");
        requestParams.addBodyParameter("pt", "2");
        requestParams.addBodyParameter("radius", "0");
        requestParams.addBodyParameter("sort", "1");
        requestParams.addBodyParameter("ver", "1.1");

        httpUtils.send(HttpRequest.HttpMethod.POST, ApiConfig.URL, requestParams, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String data = responseInfo.result;
                FavoriteList favoriteList = JSON.parseObject(data, FavoriteList.class);
                if (page == 1 && favoriteList != null) {
                    listFavorite.clear();
                    listFavorite.addAll(favoriteList.getData().getList());
                    favoriteFragmentAdapter.notifyDataSetChanged();
                }
                pullToRefreshListView.onRefreshComplete();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(getActivity(), "当前网络有问题，请重新加载", Toast.LENGTH_LONG).show();
            }
        });

    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        page = 1;
        loadData();
    }


    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        page++;
        loadData();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        String favorableUrlId =listFavorite.get(position-1).getId();
        String favorableUrl = ApiConfig.getFavorableUrl(favorableUrlId);

        Intent intent=new Intent(getActivity(), SpecialDetailActivity.class);
        Bundle bundle=new Bundle();

        bundle.putString("URL", favorableUrl);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
